﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpShare.Storage;
using SharpShare.Diagnostics;

namespace SharpShare.Afp.Protocol.Handlers {
    internal class AfpSyncDirectoryRequestHandler : IAfpRequestHandler, ILogProvider {
        public byte CommandCode {
            get { return 78; }
        }

        public AfpResultCode Process(IAfpSession session, DsiHeader dsiHeader, AfpStream requestStream, AfpStream responseStream) {
            requestStream.ReadPadding();

            ushort volumeId = requestStream.ReadUInt16();
            uint directoryId = requestStream.ReadUInt32();

            IAfpVolume volume = session.GetVolume(volumeId);
            if (volume == null)
                return AfpResultCode.FPObjectNotFound;

            IStorageContainer container = volume.GetNode(directoryId).AsContainer();

            if (container == null)
                return AfpResultCode.FPParamErr;

            var forksInContainer = session.ListForks().Where(f => f.File.IsContainedWithin(container));

            foreach (IAfpFork fork in forksInContainer) {
                try {
                    fork.DataProvider.Flush(true);
                } catch (Exception ex) {
                    Log.Add(this, EntryType.Warning, "Unable to synchronize fork '{0}': {1}", ex);
                }
            }

            return AfpResultCode.FPNoErr;
        }

        #region ILogProvider Members

        string ILogProvider.Name {
            get { return "AFP Sync Dir"; }
        }

        #endregion
    }
}
